package com.hrp.service;

import com.hrp.common.JdbcUtils;
import com.hrp.config.DruidConfiguration;
import com.hrp.domain.*;
import com.hrp.hrpdao.CommonDao;
import com.hrp.hrpdao.JxkhzbDao;
import com.hrp.hrpdao.JxkhzqDao;
import com.hrp.hrpdao.JxksdmkDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2018/8/10 0010.
 */
@Service
public class CommonService {


    private static final Logger log = LoggerFactory.getLogger(CommonService.class);

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private JxksdmkDao jxksdmkDao;

    @Autowired
    private JxkhzqDao jxkhzqDao;


    @Autowired
    private JdbcTemplate jdbcTemplate;



    @Value("${hrp.showflag}")
    public  String showflag;


    public List<Combox> getKslb(){
        List<Yydic> listdic= commonDao.getYydicBylbdm("1");
        List<Combox> comList = new ArrayList<>();
        Combox box = new Combox();

        box.setId("-1");
        box.setText("全部科室");
        box.setSelected(true);
        comList.add(box);
        for(Yydic dic:listdic){
            box = new Combox();
            box.setId(dic.getId().toString());
            box.setText(dic.getName());
            comList.add(box);
        }
        return comList;
    }

    public List<Tree>  getJxksTree(){
        List<Yydic> listdic= commonDao.getYydicBylbdm("1");

        List<Tree> resTree = new ArrayList<>();

        Tree tree = new Tree();
        tree.setId("-1");
        tree.setText("全部科室");

        List<Tree> childrenTreeList = new ArrayList<>();
        List<Jxksdmk> jxksList =  jxksdmkDao.getAllJxksList();
        Tree childrenTree = null;

        for(Yydic dic:listdic){
            childrenTree = new Tree();
            childrenTree.setId(dic.getId().toString());
            childrenTree.setText(dic.getName());

            List<Tree> ccChildrenList = new ArrayList<>();
            Tree ccTree =null;

            for(Jxksdmk jxks:jxksList){
                if(jxks.getKslb().toString().equals(dic.getId().toString())){
                    ccTree = new Tree();
                    ccTree.setId(jxks.getJxksdm());
                    ccTree.setText(jxks.getJxksmc());
                    ccChildrenList.add(ccTree);
                }
            }
            childrenTree.setChildren(ccChildrenList);
            childrenTreeList.add(childrenTree);
        }
        tree.setChildren(childrenTreeList);

        resTree.add(tree);
        return resTree;

    }

    public List<Combox> getKhzqList(){
        List<Jxkhzq> jxkhzqList= jxkhzqDao.getTopKhzq();
        List<Combox> comList = new ArrayList<>();
        Combox box = new Combox();

        //box.setId("-1");
        //box.setText("全部科室");
        //box.setSelected(true);
        //comList.add(box);
        for(Jxkhzq jxkhzq:jxkhzqList){
            box = new Combox();
            box.setId(jxkhzq.getId().toString());
            box.setText(jxkhzq.getZqmc());
            comList.add(box);
        }
        comList.get(comList.size()-1).setSelected(true);
        return comList;
    }

    public List<Map<String,Object>> getLcjj(Integer zqid){
        return commonDao.getLcjj(zqid);

    }

    public List<Combox> getDicList(Integer id,String lbdm){
        List<Yydic> list = commonDao.getDicList(lbdm);
        List<Combox> listCombox = new ArrayList<>();
        Combox combox=null;
        if(id.toString().equals("-1")){
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(i.toString().equals("0")){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                }
                listCombox.add(combox);
            }
        }else{
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(list.get(i).getId().toString().equals(id.toString())){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                }
                listCombox.add(combox);
            }
        }
        return listCombox;
    }


    public void commonUpdateById(Map<String, String[]> paraMmap){
        String[] tableNames = paraMmap.get("tableName");
        String tableName = "";
        if(tableNames==null || tableNames.length==0){
            tableName="";
        }else {
            tableName=tableNames[0];
        }
        Set paramSet = paraMmap.keySet();
        Iterator iterator = paramSet.iterator();

        StringBuffer sbSqlOne = new StringBuffer();

        sbSqlOne.append(" update  ");
        sbSqlOne.append(tableName);
        sbSqlOne.append(" set ");
        //存放表字段
        StringBuffer sbUpdateSql = new StringBuffer();
        //存放表字段的值
        //StringBuffer sbSqlValue = new StringBuffer();
        while (iterator.hasNext()){
            String paramKey =iterator.next().toString();
            if(!paramKey.equalsIgnoreCase("tableName")&&!paramKey.equalsIgnoreCase("id")){
                String paramValue=paraMmap.get(paramKey)[0];
                sbUpdateSql.append(paramKey+"="+paramValue+",");
            }
        }
        String execSql = sbUpdateSql.toString().substring(0,sbUpdateSql.toString().lastIndexOf(","));
        sbSqlOne.append(execSql);
        sbSqlOne.append(" where id= "+ paraMmap.get("id")[0]);
        System.out.println(sbSqlOne);
        jdbcTemplate.execute(sbSqlOne.toString());
    }

    public void  commonAddChil(Map<String, String[]> paraMmap){
        String[] tableNames = paraMmap.get("tableName");
        String tableName = "";
        if(tableNames==null || tableNames.length==0){
            tableName="";
        }else {
            tableName=tableNames[0];
        }
        Set paramSet = paraMmap.keySet();
        Iterator iterator = paramSet.iterator();

        StringBuffer sbSqlOne = new StringBuffer();

        sbSqlOne.append(" insert into ");
        sbSqlOne.append(tableName);
        sbSqlOne.append(" ( ");
        //存放表字段
        StringBuffer sbSqlKey = new StringBuffer();
        //存放表字段的值
        StringBuffer sbSqlValue = new StringBuffer();
        while (iterator.hasNext()){
            String paramKey =iterator.next().toString();
            if(!paramKey.equalsIgnoreCase("tableName")&&!paramKey.equalsIgnoreCase("id")){
                sbSqlKey.append(paramKey+",");
                String paramValue=paraMmap.get(paramKey)[0];
                sbSqlValue.append(paramValue+",");
                System.out.println(sbSqlKey+":"+sbSqlValue);
            }
        }
        String columName = sbSqlKey.toString().substring(0,sbSqlKey.toString().lastIndexOf(","));
        sbSqlOne.append(columName);
        sbSqlOne.append(")");
        sbSqlOne.append("values");
        sbSqlOne.append("(");
        String columValueName=sbSqlValue.toString().substring(0,sbSqlValue.toString().lastIndexOf(","));
        sbSqlOne.append(columValueName);
        sbSqlOne.append(")");
        System.out.println(sbSqlOne);
        jdbcTemplate.execute(sbSqlOne.toString());
    }


    /***
     * 公共添加方法
     * @param paraMmap
     * @return
     */
    public ResponseData commomAdd(Map<String, String[]> paraMmap) {
        if(paraMmap.size()<1){
            return  ResponseData.build(500,"不存在需要保存的数据");
        }else{
            try{
                String[] tableNames = paraMmap.get("tableName");
                String tableName = "";
                if(tableNames==null || tableNames.length==0){
                    tableName="";
                }else {
                    tableName=tableNames[0];
                }





                StringBuilder existSqlsbByName = new StringBuilder();
                existSqlsbByName.append(" select * from "+ tableName +" where name="+paraMmap.get("name")[0]+"");
                System.out.println(existSqlsbByName);
                List<Map<String,Object>> listMapresultName = jdbcTemplate.queryForList(existSqlsbByName.toString());

                if(listMapresultName!=null && listMapresultName.size()>0){
                    return ResponseData.build(600,"名称重复");
                }



                StringBuilder existSqlsb = new StringBuilder();
                existSqlsb.append(" select * from "+ tableName +" where id="+paraMmap.get("id")[0]+"");
                System.out.println(existSqlsb);
                List<Map<String,Object>> listMapresult = jdbcTemplate.queryForList(existSqlsb.toString());
                if(listMapresult!=null && listMapresult.size()>0){
                    commonUpdateById(paraMmap);
                }else{
                    commonAddChil(paraMmap);
                }
                return ResponseData.build(200,"保存数据成功");
            }catch (Exception e){
                return ResponseData.build(500,"保存数据失败");
            }


        }
    }

    /**
     * 公共获取数据分页胡方法
     * @param page,rows,tableName
     * @param tableName前台传入表格名称
     * @param paraMmap
     * @return
     */
    public Map<String, Object> commonGetListByPage(Map<String, String[]> paraMmap) {
        Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map
        if(paraMmap.get("page")==null || paraMmap.get("page").length < 1 || "".equalsIgnoreCase(paraMmap.get("page")[0]) || paraMmap.get("rows")==null || paraMmap.get("rows").length < 1 || "".equalsIgnoreCase(paraMmap.get("rows")[0])) {
            log.info("公共数据方法commonGetListByPage的参数page或者rows存在异常");
            return  jsonMap;
        }else{
            String pageStr=paraMmap.get("page")[0];
            String rowsStr = paraMmap.get("rows")[0];

            Integer page = Integer.parseInt(pageStr);
            Integer rows = Integer.parseInt(rowsStr);

            Integer startIndex = (page-1)*rows;
            Integer endIndex = page*rows;
            String tableName = paraMmap.get("tableName")[0];

            StringBuilder sbSql = new StringBuilder();
            sbSql.append("select * from (select *,ROW_NUMBER() over(order by id) row from "+tableName+" ) T where row between "+startIndex+" and "+endIndex+" ");

            StringBuilder sbSqlTwo = new StringBuilder();
            sbSqlTwo.append("select * from  " + tableName);

            try{
                List<Map<String,Object>> listMap =jdbcTemplate.queryForList(sbSql.toString());
                List<Map<String,Object>> allListMap =jdbcTemplate.queryForList(sbSqlTwo.toString());
                jsonMap.put("total", allListMap.size());//total键 存放总记录数，必须的
                jsonMap.put("rows", listMap);//rows键 存放每页记录 list
                return jsonMap;
            }catch (Exception e){
                return jsonMap;
            }
        }
    }

    public List<Combox> getUimssVarietiesDropList(Integer id,String username) {

        //设置数据查看权限
        List<Integer> showList = new ArrayList<>();
        showList.add(0);
        Integer show  = showflag.indexOf(username);
        if(show>-1){
            showList.add(1);
        }



        List<UimssVarieties> list = commonDao.getUimssVarietiesDropList("",showList);
        List<Combox> listCombox = new ArrayList<>();
        Combox combox=null;
        if(id.toString().equals("-1")){
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(i.toString().equals("0")){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                    combox.setValue(list.get(i).getPrice().toString());
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setValue(list.get(i).getPrice().toString());
                }
                listCombox.add(combox);
            }
        }else{
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(list.get(i).getId().toString().equals(id.toString())){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                    combox.setValue(list.get(i).getPrice().toString());
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setValue(list.get(i).getPrice().toString());
                }
                listCombox.add(combox);
            }
        }
        return listCombox;
    }

    public List<Combox> getUimssSupplierDropList(Integer id) {

        List<SupplierInformatrion> list = commonDao.getUimssSupplierDropList("");
        List<Combox> listCombox = new ArrayList<>();
        Combox combox=null;
        if(id.toString().equals("-1")){
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(i.toString().equals("0")){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                }
                listCombox.add(combox);
            }
        }else{
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(list.get(i).getId().toString().equals(id.toString())){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                }
                listCombox.add(combox);
            }
        }
        return listCombox;
    }

    public List<Combox> getUimssReceiverDropList(Integer id) {
        List<ReceiverInformation> list = commonDao.getUimssReceiverDropList("");
        List<Combox> listCombox = new ArrayList<>();
        Combox combox=null;
        if(id.toString().equals("-1")){
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(i.toString().equals("0")){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                }
                listCombox.add(combox);
            }
        }else{
            for(Integer i=0;i<list.size();i++){
                combox = new Combox();
                if(list.get(i).getId().toString().equals(id.toString())){
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                    combox.setSelected(true);
                }else{
                    combox.setId(list.get(i).getId().toString());
                    combox.setText(list.get(i).getName());
                }
                listCombox.add(combox);
            }
        }
        return listCombox;
    }

    public List<Tree> getUimssVarietiesTree(String  searchValue,String username) {


        //设置数据查看权限
        List<Integer> showList = new ArrayList<>();
        showList.add(0);
        Integer show  = showflag.indexOf(username);
        if(show>-1){
            showList.add(1);
        }



        List<UimssVarieties> list = commonDao.getUimssVarietiesDropList(searchValue,showList);

        List<Tree> resTree = new ArrayList<>();

        Tree tree = new Tree();
        tree.setId("-1");
        tree.setText("全部分类");

        List<Tree> childrenTreeList = new ArrayList<>();

        Tree childrenTree = null;

        for(UimssVarieties dic:list){
            childrenTree = new Tree();
            childrenTree.setId(dic.getId().toString());
            childrenTree.setIconCls("");
            childrenTree.setChecked(true);
            childrenTree.setText(dic.getName());
            childrenTreeList.add(childrenTree);
        }
        tree.setChildren(childrenTreeList);

        resTree.add(tree);
        return resTree;
    }

    public List<Tree> getUimssSupplierTree(String searchValue) {

        List<SupplierInformatrion> list = commonDao.getUimssSupplierDropList(searchValue);

        List<Tree> resTree = new ArrayList<>();

        Tree tree = new Tree();
        tree.setId("-1");
        tree.setText("全部分类");

        List<Tree> childrenTreeList = new ArrayList<>();

        Tree childrenTree = null;

        for(SupplierInformatrion dic:list){
            childrenTree = new Tree();
            childrenTree.setId(dic.getId().toString());
            childrenTree.setIconCls("");
            childrenTree.setChecked(true);
            childrenTree.setText(dic.getName());
            childrenTreeList.add(childrenTree);
        }
        tree.setChildren(childrenTreeList);

        resTree.add(tree);
        return resTree;
    }

    public List<Tree> getUimssReceiverTree(String searchValue) {

        List<ReceiverInformation> list = commonDao.getUimssReceiverDropList(searchValue);

        List<Tree> resTree = new ArrayList<>();

        Tree tree = new Tree();
        tree.setId("-1");
        tree.setText("全部分类");

        List<Tree> childrenTreeList = new ArrayList<>();

        Tree childrenTree = null;

        for(ReceiverInformation dic:list){
            childrenTree = new Tree();
            childrenTree.setId(dic.getId().toString());
            childrenTree.setIconCls("");
            childrenTree.setChecked(true);
            childrenTree.setText(dic.getName());
            childrenTreeList.add(childrenTree);
        }
        tree.setChildren(childrenTreeList);

        resTree.add(tree);
        return resTree;
    }
}
